package com.shuai.starter.bootstrap;

import com.shuai.frame.factory.ServiceProxyFactory;
import com.shuai.starter.annotation.RpcConsumer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.lang.reflect.Field;

/**
 * @author bxs
 * @version 1.0
 * @Date 2024/7/31
 */
@Slf4j
public class RpcConsumerBootstrap implements BeanPostProcessor {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        Class<?> beanClass = bean.getClass();
        Field[] fields = beanClass.getDeclaredFields();
        for (Field field : fields) {
            RpcConsumer annotation = field.getAnnotation(RpcConsumer.class);
            if (annotation == null) {
                continue;
            }
            Class<?> interfaceClass = annotation.interfaceClass();
            if (interfaceClass == void.class) {
                interfaceClass = bean.getClass().getInterfaces()[0];
            }
            field.setAccessible(true);
            try {
                field.set(bean, ServiceProxyFactory.getProxy(interfaceClass));
                field.setAccessible(false);
            } catch (IllegalAccessException e) {
                log.error("为类{}中对象{}注入代理对象失败", beanClass.getName(), field.getName());
                throw new RuntimeException("为对象注入代理对象失败", e);
            }
            log.info("为类{}中对象{}创建动态代理成功", beanClass.getName(), field.getName());
        }
        return bean;
    }
}
